import orgCtrl from '@/ts/controller'
import { TargetType } from '@/ts/core'
import { model } from '@/ts/base'
import { TabItemsInfo } from '@/ts/base/model'
import { IPortal } from './portalType'
import Operate from './operate'

class Portal {
  _portalModel: IPortal[]
  _diskInfo: model.DiskInfoType
  constructor() {
    this._portalModel = []
    this._diskInfo = {} as model.DiskInfoType
  }

  getPortal() {
    return this._portalModel
  }

  /** 加载沟通未读消息数量 */
  loadMsgCount() {
    return orgCtrl.chats
      .map(i => {
        return i.isMyChat ? i.badgeCount : 0
      })
      .reduce((total, count) => total + count, 0)
  }

  /** 加载同事数量 */
  loadMembersCount() {
    return orgCtrl.user.companys
      .map(i => i.members.map(i => i.id))
      .reduce(
        (ids, current) => [...ids, ...current.filter(i => !ids.includes(i))],
        []
      ).length
  }

  /** 加载办事数量 */
  async loadTaskCount() {
    const todoCount = (await orgCtrl.work.loadTodos()).length
    const doneTaskCount = await orgCtrl.work.loadTaskCount('已办')
    const myTaskCount = await orgCtrl.work.loadTaskCount('发起的')
    const copyTaskCount = await orgCtrl.work.loadTaskCount('抄送')
    return {
      todoCount,
      doneTaskCount,
      myTaskCount,
      copyTaskCount
    }
  }

  /** 加载关系数量 */
  loadRelationCount() {
    return orgCtrl.chats.filter(
      i => i.isMyChat && i.typeName !== TargetType.Group
    ).length
  }

  /** 加载文件信息 */
  loadFileCount() {
    orgCtrl.user.getDiskInfo().then(value => {
      this._diskInfo = value!
    })
  }

  /** 沟通信息 */
  chatsModel(): IPortal {
    return {
      title: '沟通',
      extra: {
        // content: `未读消息 · ${this.loadMsgCount()}`,
        content: '未读消息',
        afterIcon: 'tmicon-angle-right',
        size: 24
      },
      info: [
        {
          infoTitle: '好友(人)',
          count: '--' //this.unitConverter(orgCtrl.user.members.length)
        },
        {
          infoTitle: '同事(个)',
          count: '--' //this.unitConverter(this.loadMembersCount())
        },
        {
          infoTitle: '群聊(个)',
          count: '--' //this.unitConverter(
          //   orgCtrl.chats.filter(i => i.isMyChat && i.isGroup).length
          // )
        },
        {
          infoTitle: '单位(家)',
          count: '--' //this.unitConverter(orgCtrl.user.companys.length)
        }
      ]
    }
  }

  /** 办事信息 */
  async workModel(): Promise<IPortal> {
    const taskCount = await this.loadTaskCount()
    return {
      title: '办事',
      extra: {
        content: '前往审批',
        afterIcon: 'tmicon-angle-right',
        onClick: () => {
          uni.reLaunch({
            url:
              '/pages/work/work?code=' +
              TabItemsInfo.todo.code +
              '&label=' +
              TabItemsInfo.todo.label
          })
        },
        size: 24
      },
      info: [
        {
          infoTitle: TabItemsInfo.todo.label,
          count: this.unitConverter(taskCount.todoCount),
          onClick: () => {
            uni.reLaunch({
              url:
                '/pages/work/work?code=' +
                TabItemsInfo.todo.code +
                '&label=' +
                TabItemsInfo.todo.label
            })
          }
        },
        {
          infoTitle: TabItemsInfo.done.label,
          count: this.unitConverter(taskCount.doneTaskCount),
          onClick: () => {
            uni.reLaunch({
              url:
                '/pages/work/work?code=' +
                TabItemsInfo.done.code +
                '&label=' +
                TabItemsInfo.done.label
            })
          }
        },
        {
          infoTitle: TabItemsInfo.alt.label,
          count: this.unitConverter(taskCount.copyTaskCount),
          onClick: () => {
            uni.reLaunch({
              url:
                '/pages/work/work?code=' +
                TabItemsInfo.alt.code +
                '&label=' +
                TabItemsInfo.alt.label
            })
          }
        },
        {
          infoTitle: TabItemsInfo.create.label,
          count: this.unitConverter(taskCount.myTaskCount),
          onClick: () => {
            uni.reLaunch({
              url:
                '/pages/work/work?code=' +
                TabItemsInfo.create.code +
                '&label=' +
                TabItemsInfo.create.label
            })
          }
        }
      ]
    }
  }

  /** 存储信息 */
  storeModel(): IPortal {
    return {
      title: '数据',
      extra: {
        // beforeIcon: 'tmicon-plus',
        // content: '管理数据',
        content: '',
        size: 24
      },
      info: [
        {
          infoTitle: '关系(个)',
          count: this.unitConverter(this.loadRelationCount())
        },
        {
          infoTitle: '数据集(个)',
          count: this.unitConverter(this._diskInfo.collections)
        },
        {
          infoTitle: '对象数(个)',
          count: this.unitConverter(this._diskInfo.objects)
        },
        {
          infoTitle: '文件(个)',
          count: this.unitConverter(this._diskInfo.filesCount)
        }
      ]
    }
  }

  /** 处理数字展示 */
  unitConverter(num: number | string): string | number {
    if (typeof num === undefined || typeof num === null) return '0'
    const converter = num.toString()
    if (converter.length > 4) {
      const newStr = `${converter.substring(
        0,
        converter.length - 4
      )}.${converter.substring(converter.length - 4, converter.length - 2)}`
      if (newStr.endsWith('00')) {
        return `${newStr.substring(0, newStr.length - 3)}万`
      }
      if (newStr.endsWith('0')) {
        return `${newStr.substring(0, newStr.length - 1)}万`
      }
      return `${newStr}万`
    }
    return num
  }

  /** 初始化 */
  async initPortal() {
    this.loadFileCount()
    this._portalModel = [
      Operate.getOperateModel(),
      // this.chatsModel(),
      await this.workModel(),
      this.storeModel()
    ]
  }
}

export default new Portal()
